package view;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import model.User;
import service.UserService;
import utils.PasswordUtil;
import java.util.prefs.Preferences;

public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JCheckBox rememberMeCheckBox;
    private UserService userService;
    private Preferences prefs;
    
    public LoginFrame() throws Exception {
        this.userService = new UserService();
        this.prefs = Preferences.userRoot().node(this.getClass().getName());
        initComponents();
        loadSavedCredentials();
        setTitle("成绩管理系统 - 登录");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        setLocationRelativeTo(null);
        setResizable(false);
    }
    
    private void initComponents() {
        // 主面板使用GridBagLayout
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBorder(new EmptyBorder(20, 40, 20, 40));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 标题标签
        JLabel titleLabel = new JLabel("成绩管理系统", SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        gbc.gridx = 0; gbc.gridy = 0;
        gbc.gridwidth = 2;
        mainPanel.add(titleLabel, gbc);
        
        // 用户名输入
        gbc.gridwidth = 1;
        gbc.gridy = 1;
        mainPanel.add(new JLabel("用户名："), gbc);
        
        usernameField = new JTextField(15);
        gbc.gridx = 1;
        mainPanel.add(usernameField, gbc);
        
        // 密码输入
        gbc.gridx = 0; gbc.gridy = 2;
        mainPanel.add(new JLabel("密码："), gbc);
        
        passwordField = new JPasswordField(15);
        gbc.gridx = 1;
        mainPanel.add(passwordField, gbc);
        
        // 记住密码选项
        gbc.gridx = 0; gbc.gridy = 3;
        gbc.gridwidth = 2;
        rememberMeCheckBox = new JCheckBox("记住密码");
        mainPanel.add(rememberMeCheckBox, gbc);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton loginButton = new JButton("登录");
        JButton resetButton = new JButton("重置");
        //更新乱码
        loginButton.addActionListener(e -> handleLogin());
        resetButton.addActionListener(e -> handleReset());
        
        buttonPanel.add(loginButton);
        buttonPanel.add(resetButton);
        
        gbc.gridy = 4;
        mainPanel.add(buttonPanel, gbc);
        
        add(mainPanel);
        
        // 设置回车键触发登录
        getRootPane().setDefaultButton(loginButton);
    }
    
    private void handleLogin() {
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());
        
        if (username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名和密码不能为空！");
            return;
        }
        
        try {
            User user = userService.login(username, password);
            if (user != null) {
                // 检查用户状态
                if (user.getStatus() == 0) {  // 0表示禁用状态
                    JOptionPane.showMessageDialog(this,
                        "该账号已被禁用，请联系管理员！",
                        "登录失败",
                        JOptionPane.ERROR_MESSAGE);
                    return;
                }
                
                // 记住密码
                if (rememberMeCheckBox.isSelected()) {
                    saveCredentials(username, password);
                } else {
                    clearSavedCredentials();
                }
                
                // 更新最后登录时间
                userService.updateLastLogin(user.getId());
                
                // 打开主界面
                SwingUtilities.invokeLater(() -> {
                    new MainFrame(user).setVisible(true);
                    dispose();
                });
            } else {
                JOptionPane.showMessageDialog(this,
                    "用户名或密码错误！",
                    "登录失败",
                    JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                "登录失败：" + e.getMessage(),
                "错误",
                JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }
    
    private void handleReset() {
        usernameField.setText("");
        passwordField.setText("");
        rememberMeCheckBox.setSelected(false);
    }
    
    private void saveCredentials(String username, String password) throws Exception {
        prefs.put("username", username);
        prefs.put("password", PasswordUtil.encrypt(password));
        prefs.putBoolean("rememberMe", true);
    }
    
    private void loadSavedCredentials() throws Exception {
        if (prefs.getBoolean("rememberMe", false)) {
            String username = prefs.get("username", "");
            String encryptedPassword = prefs.get("password", "");
            
            usernameField.setText(username);
            passwordField.setText(PasswordUtil.decrypt(encryptedPassword));
            rememberMeCheckBox.setSelected(true);
        }
    }
    
    private void clearSavedCredentials() {
        prefs.remove("username");
        prefs.remove("password");
        prefs.remove("rememberMe");
    }
} 